package com.ikun.admin.common.exception;

import com.ikun.admin.common.constant.CommonConstant;
import com.ikun.admin.modules.sys.entity.LogError;
import com.ikun.admin.modules.sys.iservice.ILogService;
import com.ikun.common.exception.ExceptionUtils;
import com.ikun.common.exception.MyException;
import com.ikun.common.result.Result;
import com.ikun.common.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @ClassName GlobalExceptionHandler
 * @Description: 全局异常处理器
 * @CreateDate: 2024/4/1 15:15
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private ILogService iLogService;

    /**
     * 处理Exception
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception exception) {
        log.error(exception.getMessage(), exception);

        saveLog(exception, CommonConstant.SYS_ERROR);

        return new Result().error("系统异常");
    }

    /**
     * 处理MyException
     * @param myException
     * @return
     */
    @ExceptionHandler(MyException.class)
    public Result handleMyException(MyException myException) {
        log.error(myException.getMessage(), myException);

        saveLog(myException, CommonConstant.BUSINESS_ERROR);

        return new Result().error(myException.getMessage());
    }

    /**
     * 处理sql异常
     * @param sqlException
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public Result handleSqlException(SQLException sqlException) {
        log.error(sqlException.getMessage(), sqlException);

        saveLog(sqlException, CommonConstant.SQL_ERROR);
        //todo 管理员(发送邮件或短信通知)

        return new Result().error("系统异常");
    }

    /**
     * 保存错误日志
     *
     * @param exception
     */
    public void saveLog(Exception exception,Integer type) {
        //获取错误堆栈信息
        String errorStackTrace = ExceptionUtils.getErrorStackTrace(exception);
        LogError logError = new LogError();
        logError.setErrorInfo(errorStackTrace);
        logError.setType(type);
        logError.setRequestUri(HttpContextUtils.getRequestUri());
        logError.setRequestMethod(HttpContextUtils.getRequestMethod());
        logError.setRequestParams(HttpContextUtils.getRequestParams());

        //保存数据库
        iLogService.saveLogError(logError);

    }

}
